<?php declare(strict_types=1);

echo (new AliSms())->input('13800138000','SMS_168591805','{"code":11111}','签名','120IkTnta6maf43d','112ikPWWmBnvCXNKmCOAdjkhg110');

class AliSms
{
    public function input($mobile,$templateCode,$templateParam,$signName,$accessKeyId,$accessKeySecret)
    {
        $secret = $accessKeySecret.'&';
        $arr = [
            "Action"=> 'SendSms',
            "AccessKeyId" => $accessKeyId,
            'Format'=> 'JSON', 
            'PhoneNumbers'  => $mobile,
            'RegionId'  => 'cn-hangzhou', 
            'SignName'=> $signName,
            'SignatureMethod'   => 'HMAC-SHA1',            
            'SignatureNonce'    => uniqid('wenchu'),
            'SignatureVersion'  => '1.0', 
            'TemplateCode'      => $templateCode,         
            'TemplateParam'     => $templateParam,
            'Timestamp'         => gmdate("Y-m-d\\TH:i:s\\Z"),
            'Version'           => "2017-05-25"
        ];
        $arr['Signature'] = $this->sign($arr, $secret);
        $path = $this->getUrl($arr);
        return $this->send($path);
    }
    private function send(string $path)
    {
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
        ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)");
        return file_get_contents('http://dysmsapi.aliyuncs.com' . $path,false, stream_context_create($stream_opts));
    }
    private function getUrl(array $arr)
    {
        $path = '/?';
        foreach ($arr as $key => $val) {
            $path .= $key . '=' . $this->encode($val) . "&";
        }
        return trim($path, '&');
    }
    private function sign(array $arr, string $secret)
    {
        ksort($arr);
        $path = '';
        foreach ($arr as $key => $val) {
            $path .= $key . "=" . $this->encode($val) . "&";
        }
        $encode = 'GET&%2F&' . $this->encode(trim($path, '&'));
        return base64_encode(hash_hmac('sha1', $encode, $secret, true));
    }
    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }
}

